package com.idea.cery.springboot1.controller;

import com.idea.cery.springboot1.base.MqProduct;
import com.idea.cery.springboot1.base.core.Result;
import com.idea.cery.springboot1.base.core.ResultGenerator;
import com.idea.cery.springboot1.bean.SpeechResult;
import com.idea.cery.springboot1.util.PushCallback;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import javax.jms.Destination;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author cery
 */
@Api(description = "基础控制类访问，静态资源访问")
@Controller
@RequestMapping("tc")
public class TestController {
    @Autowired
    private MqProduct            mqProduct;
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @Value("${random.int}")
    private String str;
    //配置文件 properties 属性 值
    @Value("${my.secret}")
    private String secret;
    @Value("${my.number}")
    private String number;
    @Value("${my.bignumber}")
    private String bignumber;
    @Value("${my.uuid}")
    private String uuid;
    @Value("${my.number.less.ten}")
    private String numLessNum;
    @Value("${my.number.range}")
    private String range;

    private static final String HOST = "tcp://127.0.0.1:1883";
    private String TOPIC;
    private String MESSAGE;
    private static final String clientid = "e92855430557caf1";

    private MqttClient client;
    private MqttTopic topic;

    private String userName = "admin";
    private String passWord = "admin";

    private MqttMessage message;


    @ApiOperation(value = "外部配置 占位符 ${ }")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    @ResponseBody
    public String index() {
        System.out.println("进入tc/index controller。");
        System.out.println("直接获取random值：" + str);
        System.out.println("配置获取random value值：" + secret);
        System.out.println("配置获取random int值：" + number);
        System.out.println("配置获取random bignumber值：" + bignumber);
        System.out.println("配置获取random uuid值：" + uuid);
        System.out.println("配置获取random numLessNum值：" + numLessNum);
        System.out.println("配置获取random range值：" + range);

        return "测试成功！ 配置初始值：" + str;
    }

    @RequestMapping(value = "html", method = RequestMethod.GET)
    public String indexHtml() {
        System.out.println("返回静态页面");
        return "index";
    }

    @ApiOperation(value = "测试传参方式0", notes = "访问路径 tc/cs?str=123", httpMethod = "GET")
    @RequestMapping(value = "cs") //访问路径 tc/cs?str=123
    @ResponseBody
    public String indexCS(String str) {
        System.out.println("请求参数路径1");
        return "index" + str;
    }

    @ApiOperation(value = "测试传参方式1", notes = "访问路径：/kh/18/1", httpMethod = "GET")
    @RequestMapping(value = "/kh/{age}/{sta}")//访问路径：/kh/18/1
    @ResponseBody
    public String indexKH(@PathVariable int age, @PathVariable int sta) {
        System.out.println("请求参数路径2");
        return "age：" + age + " sta：" + sta;
    }

    @ApiOperation(value = "测试传参方式2", notes = "访问路径(表单)：/bd?id=5", httpMethod = "GET")
    @RequestMapping(value = "/bd") //访问路径(表单)：/bd?id=5
    @ResponseBody
    public Date indexBD(@RequestParam("date") Date date) {
        /**
         * 测试 注解日期格式 输入输出
         */
        System.out.println("请求参数路径3");
        return date;
    }

    @ApiOperation(value = "activeMQ 队列", notes = "访问路径(表单)：/mq/cery/1", httpMethod = "GET")
    @RequestMapping(value = "/mq/{name}/{str}")//访问路径：/kh/18/1
    @ResponseBody
    public String activeMQ(@PathVariable String name, @PathVariable String str) {
        //监听的destination 名称 设置在配置文件中

        //Destination des = new ActiveMQQueue(name);
        //mqProduct.sendMessaging(des, str);

        /**
         * 要开启发布订阅Topic 要配置 pub-sub-domain=true(默认为false)
         */
        ActiveMQTopic destopic = new ActiveMQTopic(name);
        mqProduct.sendMessaging(destopic, str);

        return "完成";
    }

    @ApiOperation(value = "mqtt 队列", notes = "访问路径(表单)：/mq/cery/1", httpMethod = "GET")
    @RequestMapping(value = "/mqtt/{name}/{str}")//访问路径：/kh/18/1
    @ResponseBody
    public String doPublish(@PathVariable String name, @PathVariable String str) throws MqttException {
        //获取前台传过来的两个参数
        TOPIC="/arobot/server/F2/e92855430557caf1";
        MESSAGE=str;
        //new mqttClient
        //MemoryPersistence设置clientid的保存形式，默认为以内存保存
        client = new MqttClient(HOST, clientid, new MemoryPersistence());
        //与activeMQ连接的方法
        connect();
        //new mqttMessage
        message = new MqttMessage();
        //设置服务质量
        message.setQos(2);
        //设置是否在服务器中保存消息体
        message.setRetained(true);
        //设置消息的内容
        message.setPayload(MESSAGE.getBytes());
        //发布
        publish(topic, message);

        System.out.println("已发送");

        return "result";
    }


    @ApiOperation(value = "外部测试", notes = "访问路径(表单)：/getRequestValue/cery", httpMethod = "POST")
    @RequestMapping(value = "/getRequestValue/{str}")//访问路径：/kh/18/1
    @ResponseBody
    public Result getRequestValue(@PathVariable String str) {
        //监听的destination 名称 设置在配置文件中
        if(str == null || str.length()==0){
            return ResultGenerator.genFailResult("参数不能为空");
        }
        List list = new ArrayList();
        SpeechResult sr = new SpeechResult();
        sr.setIndex("1");
        sr.setAction("");
        sr.setContent("打开设置界面");
        sr.setFragment("SetupFragment");

        SpeechResult sr1 = new SpeechResult();
        sr1.setIndex("2");
        sr.setAction("");
        sr1.setContent("打开语音设置界面");
        sr1.setFragment("VoiceFragment");

        list.add(sr);
        list.add(sr1);

        return ResultGenerator.genSuccessResult(list);
    }
    @ApiOperation(value = "外部测试", notes = "访问路径(表单)：/getRequestValue", httpMethod = "POST")
    @RequestMapping(value = "/getRequestValue")//访问路径：/kh/18/1
    @ResponseBody
    public Result getRequestValue() {
        //监听的destination 名称 设置在配置文件中
        if(str == null || str.length()==0){
            return ResultGenerator.genFailResult("参数不能为空");
        }
        List list = new ArrayList();
        SpeechResult sr = new SpeechResult();
        sr.setIndex("1");
        sr.setAction("");
        sr.setContent("打开设置界面");
        sr.setFragment("SetupFragment");

        SpeechResult sr1 = new SpeechResult();
        sr1.setIndex("2");
        sr.setAction("");
        sr1.setContent("打开语音设置界面");
        sr1.setFragment("VoiceFragment");

        list.add(sr);
        list.add(sr1);

        return ResultGenerator.genSuccessResult(list);
    }


    private void connect() {
        // new mqttConnection 用来设置一些连接的属性
        MqttConnectOptions options = new MqttConnectOptions();
        // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
        // 换而言之，设置为false时可以客户端可以接受离线消息
        options.setCleanSession(false);
        // 设置连接的用户名和密码
        options.setUserName(userName);
        options.setPassword(passWord.toCharArray());
        // 设置超时时间
        options.setConnectionTimeout(10);
        // 设置会话心跳时间
        options.setKeepAliveInterval(20);
        try {
            // 设置回调类
            client.setCallback(new PushCallback());
            // 连接
            client.connect(options);
            // 获取activeMQ上名为TOPIC的topic
            topic = client.getTopic(TOPIC);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void publish(MqttTopic topic, MqttMessage message) throws MqttPersistenceException,  MqttException {
        // 发布的方法
        // new mqttDeliveryToken
        MqttDeliveryToken token = topic.publish(message);
        // 发布
        token.waitForCompletion();
        System.out.println("message is published completely! "
                + token.isComplete());
    }

}
